package com.zhanvie.thread;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class CustomThreadFactory implements ThreadFactory {

    private ThreadGroup group;
    private AtomicInteger threadNum = new AtomicInteger(0);
    private String namePrefix;

    public CustomThreadFactory(String namePrefix) {
        this.namePrefix = namePrefix + "-thread-";
        SecurityManager securityManager = System.getSecurityManager();
        group = (securityManager != null) ? securityManager.getThreadGroup() :
                Thread.currentThread().getThreadGroup();
    }

    public Thread newThread(Runnable r) {
        Thread thread = new Thread(group, r,
                namePrefix + threadNum.incrementAndGet(), 0);
        if (thread.isDaemon()) {
            thread.setDaemon(false);
        }
        if (thread.getPriority() != Thread.NORM_PRIORITY) {
            thread.setPriority(Thread.NORM_PRIORITY);
        }
        return thread;
    }

}
